//单独运行无效，需要搭配其他脚本一起运行

//生成最小值到最大值之间的随机整数
function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}


// 记录实时点赞数据
function record_like(write_record, data) {
    if (write_record){
        files.write("点赞实时数据.txt", JSON.stringify(data,null,2), "utf-8");
    }
}


//小米有些时候识别不到节点
function swipeOnce(lastT,slidesign,author) {
    if (devicebrand !== "XIAOMI") { return [lastT,slidesign,author] }
    let currentT = +new Date()
    if (currentT - lastT < 5*1000){ return [lastT,slidesign,author] }
    //log("currentT - lastT = ",currentT - lastT)
    if (packageName("com.smile.gifmaker").textMatches(/我|消息|粉丝|关注/).findOnce()) {return [currentT,slidesign,author]}
    //if (!id("com.smile.gifmaker:id/texture_view_frame").className("android.widget.FrameLayout").visibleToUser().findOnce()) {return [lastT,slidesign,author] }
    if (!id("com.smile.gifmaker:id/root").desc("暂停视频").visibleToUser().findOnce()) {return [currentT,slidesign,author] }
    
    let current_author
    let ele = id("com.smile.gifmaker:id/user_name_text_view").textStartsWith("@").visibleToUser().findOnce()
    if (ele) {
        current_author = ele.text()
        if (author && current_author === author) {return [currentT,slidesign,current_author] }
    }
    
    if (devicebrand === "XIAOMI") {
        log("当前手机品牌为小米，准备查找展开按钮")
        //swipe(500,300,500,400,500)
        let ele = text("展开").findOne(500)
        if (ele) {
            log("已找到--展开")
            slidesign = true
            currentT = +new Date()
            let x = ele.bounds().centerX()
            let y =  ele.bounds().centerY()
            log("y坐标 = ",y)
            if (y > 300) {
                swipe(x, y, x, y - 100, 2000)
            } else {
                swipe(x ,y, x, y + 100, 2000)
            }
        }
    }
    return [currentT,slidesign,current_author]
}



function makeRecord4userNotExists(msg) {
    filename = "用户不存在.txt"
    try {
        if (!files.exists(filename)){
            let file = open(filename, "w"); //以写入模式（"w"）打开SD卡根目录下的example.txt文件。如果文件不存在，则会自动创建该文件。
            // 写入文本内容
            file.write(msg);
            // 关闭文件
            file.close();
        }
    } catch (e) {
        let file = open("error_" + filename, "w"); 
        file.write("捕获到错误：" + e.message); // `捕获到错误：${e.message}`;
        file.close();
    }
}
function userNotExists() {
    let clicksign = false
    if (text("用户不存在").visibleToUser().findOnce()) {
        clicksign = true
    }
    if (clicksign) {
        let ele = text("确定").visibleToUser().findOnce() || desc("确定").visibleToUser().findOnce()
        if (ele) {
            if (ele.clickable) {ele.click()}
            else {click(ele.bounds().centerX(), ele.bounds().centerY())}
            sleep(500)
        }

        return true
    }
    return false
}

function userNotExists_old() {
    let clicksign = false
    if (text("用户不存在").visibleToUser().findOnce()) {
        clicksign = true
        makeRecord4userNotExists('找到：text("用户不存在")')
    } else if (desc("用户不存在").visibleToUser().findOnce()) {
        clicksign = true
        makeRecord4userNotExists('找到：desc("用户不存在")')
    }
    if (clicksign) {
        let ele = text("确定").visibleToUser().findOnce() || desc("确定").visibleToUser().findOnce()
        if (ele) {
            if (ele.clickable) {ele.click()}
            else {click(ele.bounds().centerX(), ele.bounds().centerY())}
            sleep(500)
        }

        return true
    }
    return false
}

function 横向滑动机型判断() {
    // if (devicebrand === "XIAOMI") {
    //     return true
    // }
    if (devicemodel.match(/KNT-AL10|KNT-UL10/)) {
        log("当前手机型号为 KNT-AL10 或者 KNT-UL10，将横向滑动结束'设置'程序")
        return true 
    }
    return false
}
function 横向滑动(l,r,cy) {
    if (横向滑动机型判断()) {
        if (!(r > 300 && r - l > 300)) {
            log("坐标值貌似不复合要求(r > 300 && r - l > 300)：左右及纵坐标中心值为(l,r,cy)：l = ",l,", r = ",r,", cy = ",cy)
            l = randInt(300,400)
            r = randInt(700,800)
            log("尝试随机指定一组数值进行滑动：左右及纵坐标中心值为(l,r,cy)：l = ",l,", r = ",r,", cy = ",cy)
        }
        swipe(l+5, cy, r-5, cy, 500);
        return true
    }
    return false
}
function 划掉设置() {
    // if (devicebrand === "XIAOMI") {
    //     //当前机型为小米，不做任何处理
    //     return true
    // }
    log("划掉应用信息")
    recents()
    sleep(500)
    let ele_setting = desc("设置 应用信息").className("android.widget.FrameLayout").visibleToUser().findOne(1000)
    if (ele_setting) {
        //log(ele_setting.className)
        //log(ele_setting.bounds())
        let [cy,l,r] = [ele_setting.bounds().centerY(),ele_setting.bounds().left,ele_setting.bounds().right]
        let [c,t,b] = [ele_setting.bounds().centerX(),ele_setting.bounds().top,ele_setting.bounds().bottom]
        if (横向滑动(l,r,cy)) {
            return true
        }
        // 参数：x1, y1, x2, y2, duration
        // 例如，从屏幕(100, 100)滑动到(200, 200)，滑动时间为500毫秒
        if (ele_setting.bounds().height() > 500) {
            //recents()
            //log("执行recents()")
            //sleep(500)
            swipe(c, b-30, c, t, 500);
            return true
        }
    }
    return false
}
function 点击取消(forcestop,maxcount) {
    maxcount = maxcount || 10
    log("进入点击取消")
    //log("forcestop = ",forcestop)
    while (textMatches(/要强行停止吗.*|.*强行停止.*应用.*/).findOnce() || text("快手").visibleToUser().findOnce() && text("卸载").visibleToUser().findOnce()) {
        let ele = text("取消").visibleToUser().findOnce()
        if (ele){
            sleep(200)
            if (forcestop < maxcount) {
                ele.click()
            }
            //ele.click()
            sleep(300)
            if (forcestop >= maxcount) {
                if (划掉设置()) {
                    forcestop = 0
                }
            } else {
                log("切换到首页")
                home()
            }
            sleep(2000)
            return forcestop
        } else if (text("卸载").visibleToUser().findOnce()) {
            if (forcestop >= maxcount) {
                if (划掉设置()) {
                    forcestop = 0
                }
            } 
            for (let i = 1; i < 5; i++) {
                if (packageName("com.smile.gifmaker").textMatches(/我|消息|粉丝|关注/).findOnce() || descContains('点赞').visibleToUser().findOnce()) {
                   return forcestop
                } else if (!text("卸载").visibleToUser().findOnce()) {
                    return forcestop
                } 
                sleep(500)
            }
            return forcestop
        }
        sleep(500)
    }
    return forcestop
}



function 点赞(my_count,other_count,fail_count,uplimit) {
    log("进入点赞")
    let try_count = 0
    let sleepT = randInt(50,300)
    for (let i = 1; i < 10; i++) {
        //log("i = ",i)
        var elm = clickable(true).descStartsWith("未点赞，点赞").visibleToUser().findOne(1000)
        if (elm) {
            //log("elm.desc = ",elm.desc())
            sleep(sleepT)
            elm.click()
            sleep(500)
            if (descContains('已点赞').visibleToUser().findOnce())
            {   
                log("已点赞 -> my_count")
                my_count += 1
            } else {
                if (try_count < 1) {try_count += 1; sleepT = randInt(50,150); continue}
                log("点赞失败：点赞已达上限或者其他原因")
                fail_count += 1
            }
            break
        } else if (descContains('已点赞').visibleToUser().findOnce()) {   
            log("已点赞 -> other_count")
            other_count += 1
            break
        } //else { log("已点赞 和 未点赞都未检测到") }
        
    }
    return [my_count,other_count,fail_count,uplimit]

}

function likeUptoLimit(uplimit){
    let breaksign = false
    if (uplimit > 5) {
        toastLog("点赞已达上限,即将终止脚本")
        let ele_expand = text("展开").findOnce()
        if (ele) {
            click(ele_expand.bounds().centerX(), ele_expand.bounds().centerY())
            sleep(500)
            let ele_stop = text("停止运行").findOnce()
            let ele_exit = text("退出").findOnce()
            if (ele_stop && ele_exit) {
                click(ele_stop.bounds().centerX(), ele_stop.bounds().centerY())
                sleep(300)
                click(ele_exit.bounds().centerX(), ele_exit.bounds().centerY())
            }
        }
        let ele = textMatches(/展开|隐藏|停止运行|退出/).findOnce()
        if (!ele) {
            log("退出脚本成功，已完成点赞 ",my_count + other_count," 个")
            //break
            breaksign = true
        }
    }
    return breaksign 
}


var clearlog = true
var my_count = 0
var other_count = 0
var fail_count = 0
var uplimit = 0
let success_count = my_count + other_count
let total_count = success_count + fail_count

var forcestop = 0 //强行停止次数统计 大于20次，划掉强行停止
var devicebrand = device.brand.toUpperCase()
//var devicemodel = android.os.Build.MODEL
var devicemodel = device.model
var write_record = false
if (files.exists("是否记录.txt")){
    write_record = true 
 }
//events.observeToast();
//events.on("toast",function(toast){
//log("Toast内容: " + toast.getText() + " 包名: " + toast.getPackageName());
//});
toastLog("Running...")
while (true) {
    var now = new Date()
    // 使用getHours()方法获取当前小时
    var hours = now.getHours();
    if (hours == 4 && clearlog) {
        clearlog = false
        console.clear()
        log("当前时间在4-5点之间，清理一次日志")
    }
    let temp_count = total_count
    log("[成功 / 总计 = ", success_count," / ", temp_count,"], 补赞 = ",my_count,", 首赞 = ", other_count,", 失败 = ", fail_count)

    let temp_uplimit = uplimit
    let count4break = 0
    let startT
    var slidesign = false //小米手机获取节点不正常，用滑动元素方式测试是否可以增加节点刷新成功率
    var lastT = now.getTime() //用来记录（该while循环耗时）多久未成功识别到 点赞 元素，如果超过一定时间，则滑动元素
    let meetkwai = true //遇到[确定]快手之外的应用不点击取消，即不确定的也依然要点击取消
    let lastT4meetkwai//记录 变量 meetkwai 为 false 的起始时间，当超过一段时间，比如30秒，则重新将meetkwai置为true
    while (true) {
        if (textMatches(/你今天点赞的作品数已达上限/).findOnce()){ //这个节点autojs检测不到
            toastLog("点赞失败，点赞已达上限")
            uplimit += 1
            if ( count4break > 1 ) {break}
        } else if (text("取消").visibleToUser().findOnce() && textMatches(/要强行停止吗.*|.*强行停止.*应用.*/).findOnce())  {
            if (!meetkwai) { sleep(2000); meetkwai = true; continue }
            log("已找到 强行停止/确定，取消/卸载")
            break 
        //} else if (text("快手").visibleToUser().findOnce() && text("卸载").visibleToUser().findOnce()) {
        } else if (text("卸载").visibleToUser().findOnce()) {
            //if (textMatches(/免rootyoloall|AScript|Autox.js.*|AutoJs.*/).visibleToUser().findOnce()) { sleep(500); continue }
            if  (!text("快手").visibleToUser().findOnce()) { 
                let tempT4meetkwai = +new Date()
                if (meetkwai) { if (!lastT4meetkwai || tempT4meetkwai - lastT4meetkwai > 30*1000) log("当前强行停止程序不是快手")};
                meetkwai = false;
                if (!lastT4meetkwai) {lastT4meetkwai = tempT4meetkwai;}
                if (tempT4meetkwai - lastT4meetkwai > 10*1000) {
                    lastT4meetkwai = tempT4meetkwai
                    meetkwai = true
                }
                sleep(500); 
                continue 
            }
            if ( count4break === 0 ) {startT = +new Date()}
            if ( count4break > 1 && +new Date() - startT > 5000 ) { home(); count4break = 0; break }
            count4break += 1   
        } else if (count4break > 1 && (packageName("com.smile.gifmaker").textMatches(/我|消息|粉丝|关注/).findOnce() || descContains('点赞').visibleToUser().findOnce())) {
            break
        } else {
            let ele = id("com.smile.gifmaker:id/iv_close").className("android.widget.ImageView").findOnce() //clickable(true). 关闭更新弹窗
            if (ele)
            {
                ele.click()
                sleep(100)
                if ( count4break > 1 ) {break}
            } else if (userNotExists()) {
                //检测用户不存在--弹窗
            } else {
                //text = 妥妥好评/我要吐槽 >> 点击关闭按钮
                ele = clickable(true).id("com.smile.gifmaker:id/close").className("android.widget.ImageView").visibleToUser().findOnce() 
                if (ele) {ele.click();sleep(100)}
            }
        }
        //var [lastT,slidesign,author] = swipeOnce(lastT,slidesign,author)
        sleep(500)
    }
    forcestop = 点击取消(forcestop)
    //log("forcestop = ",forcestop)
    swipeOnce()
    var [my_count,other_count,fail_count,uplimit] = 点赞(my_count,other_count,fail_count,uplimit)
    success_count = my_count + other_count
    total_count = success_count + fail_count
    if (total_count > temp_count) {
        let data = {
            "成功 / 总计":success_count + " / " + total_count,
            "补赞":my_count,
            "首赞":other_count,
            "失败":fail_count,
            //time:now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds()
            //"Current_time":now.toString()
            "时间":"时分秒：" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds()
        }
        record_like(write_record,data)
        sleep(5000)
        if (devicebrand !== "XIAOMI") {
            forcestop += 1
        }
    }
    
    //let breaksign = likeUptoLimit(uplimit) 点赞达到上限，结束任务，现在取消了（有时候点赞上限还能点，而且这个点赞上限的toast消息用autojs抓不到）
    //if (breaksign) {break}

}